<template>
  <div class="findHouse-wrapper">
    <div class="searchBar">
      <van-search
        v-model="searchVal"
        show-action
        placeholder="请输入小区或地址"
        background="none"
        @search="onSearch"
      >
        <template #label>
          <div @click="$router.push('/cityList')">{{cityname}}</div>
        </template>
        <template #action>
            <van-icon name="map-marked" @click="$router.push('/map')"/>
        </template>
      </van-search>
    </div>
    <van-sticky>
      <van-dropdown-menu active-color="#21b97a" :overlay="isMask" >
        <van-dropdown-item title="区域" ref="selectItem1">
          <van-area
            :loading="areaLoading"
            :area-list="areaList"
            @change="areaChange"
            :columns-placeholder="['请选择']"
          >
            <template #columns-bottom>
              <div class="van-picker__bottom">
                <van-button type="default" class="sm-btn">取消</van-button
                ><van-button class="big-btn" type="primary" @click="onConfirm('selectItem1')">确定</van-button>
              </div>
            </template>
          </van-area>
        </van-dropdown-item>
        <van-dropdown-item title="方式"  ref="selectItem2">
          <van-area :area-list="rentTypeList" :columns-num="1" :loading="areaLoading">
            <template #columns-bottom>
              <div class="van-picker__bottom">
                <van-button type="default" class="sm-btn">取消</van-button
                ><van-button class="big-btn" type="primary" @click="onConfirm('selectItem2')">确定</van-button>
              </div>
            </template>
          </van-area>
        </van-dropdown-item>
        <van-dropdown-item title="租金" ref="selectItem3">
          <van-area :area-list="priceList" :columns-num="1" :loading="areaLoading">
            <template #columns-bottom>
              <div class="van-picker__bottom">
                <van-button type="default" class="sm-btn">取消</van-button
                ><van-button class="big-btn" type="primary" @click="onConfirm('selectItem3')">确定</van-button>
              </div>
            </template>
          </van-area>
        </van-dropdown-item>
        <van-dropdown-item title="筛选"
          @open="openMenuLast"
          @close="closeMenuLast"
        >
          <van-popup
            v-if="popUpShow"
            @close="closePopUp"
            v-model="popUpShow"
            position="right"
            get-container="body"
            :style="{
              height: '100%',
              width: '80%',
              display: 'flex',
              flexDirection: 'column',
            }"
          >
          <!-- :loading="areaLoading" -->
            <div class="loading" v-if="areaLoading">
                  <van-loading text-color="#0094ff" color="#0094ff"  />
            </div>
            <div class="popmain">
              
              <div class="right-pop-item" v-for="v in rightPop" :key="v.title">
                <div class="pop-item-title">{{ v.title }}</div>
                <div class="pop-item-wrapper">
                  <div
                    :class="['pop-item-tag', { active: v1.active }]"
                    v-for="v1 in v.children"
                    :key="v1.value"
                    @click="toggleTags(v1)"
                  >
                    {{ v1.label }}
                  </div>
                </div>
              </div>
            </div>
            <div class="van-picker__bottom right-pop">
              <van-button type="default" class="sm-btn" @click="clearActiveTags"
                >清除</van-button
              ><van-button class="big-btn" type="primary" @click="onMoreConfirm">确定</van-button>
            </div>
          </van-popup>
        </van-dropdown-item>
      </van-dropdown-menu>
    </van-sticky>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        
      >
        <van-empty v-if="houseCount.length ==0" description="没有找到房源，请您换个搜索条件吧" />
        <house-item v-for="(v,i) in houseList" :key="i" :houseItem="v"></house-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { Toast } from 'vant';
import { mapState } from 'vuex';
import HouseItem from '@/components/HouseItem.vue';
export default {
  name:"findhouse",
  components:{
    HouseItem,
  },
  data() {
    return {
      areaList: {
        province_list: {
          100000: "区域",
          110000: "地铁",
        },
        city_list: {},
        county_list: {},
      },
      areaData: {
        区域: [],
        地铁: [],
      },
      rentTypeList: {
        province_list: {},
      },
      priceList: {
        province_list: {},
      },

      popUpShow: false,
      isMask: true,
      searchVal: "",
      rightPop: [
        {
          title: "户型",
          type: "roomType",
          children: [],
        },
        {
          title: "朝向",
          type: "oriented",
          children: [],
        },
        {
          title: "楼层",
          type: "floor",
          children: [],
        },
        {
          title: "房屋亮点",
          type: "characteristic",
          children: [],
        },
      ],
      rightPopSelected: [], //rightPop选中项
      areaLoading:true,
      houseList: [],
      pagesize:20,
      pageindex:1,
      houseCount:0,
      loading: false,
      finished: false,
      refreshing: false,
    };
  },
  created() {
    console.log('我来了,只有一次');
    //this.onLoad();
    this.gethouse();
    this.getHouseCondition();
  },
  computed:{
    ...mapState('city',['cityname','cityId'])
  },
  methods: {
    onSearch() {},
    onConfirm(key) {
      this.$refs[key].toggle();
    },
    onMoreConfirm(){
      
      this.popUpShow = false;
    },
    openMenuLast() {
      this.isMask = false;
      this.popUpShow = true;
    },
    closeMenuLast() {
      this.isMask = true;
      console.log("我关弹窗了");
    },
    closePopUp(){
      console.log("我关弹窗了");
    },
    toggleTags(item) {
      let newrightPopSelected = new Set(this.rightPopSelected);
      item.active = !item.active;
      if (item.active) {
        newrightPopSelected.add(item.value);
      } else {
        newrightPopSelected.delete(item.value);
      }
      this.rightPopSelected = [...newrightPopSelected];
      console.log(this.rightPopSelected);
    },
    clearActiveTags() {
      this.rightPopSelected = [];
      this.rightPop.forEach((item) => {
        item.children.forEach((v) => {
          v.active = false;
        });
      });
      console.log("清除成功");
    },
    areaChange(_, selectArr, index) {
      console.log(selectArr, index);
      if (selectArr[index].code) {
        //选中不为空
        const findType = selectArr[0].code;
        //this.areaFilter(this.area[findType],index)
      }
    },
    async getHouseCondition() {
      const { data } = await this.$http.getCondition({
        cityId: this.cityId,
      });
      const {
        area,
        subway,
        price,
        rentType,
        characteristic,
        floor,
        oriented,
        roomType,
      } = data.body;
      console.log(data.body);
      const rightPops = { characteristic, floor, oriented, roomType };
      this.areaLoading = false;
      this.areaData["地铁"] = subway;
      this.areaData["区域"] = area;
      this.areaFilter([area, subway]);
      this.priceList.province_list = this.priceOrRentFilter(price);
      this.rentTypeList.province_list = this.priceOrRentFilter(rentType);
      for (const key in rightPops) {
        this.rightPop.forEach((item) => {
          if (item.type == key) {
            item.children = this.addTagsActive(rightPops[key]);
          }
        });
      }
    },
    async gethouse() {
      const { data } = await this.$http.getHouse({
        cityId:this.cityId,
        start:(this.pageindex-1) * this.pagesize + 1,
        end:this.pageindex * this.pagesize,
      });
      console.log(data);
      if(this.houseCount==0) Toast('共找到'+data.body.count+'套房源')
      this.houseCount = data.body.count;
      
      const futureCount = data.body.list.length + this.houseList.length ;
      if(futureCount > this.houseCount){
        //没有更多数据了
        this.finished = true;
      } else {
        this.pageindex ++;
        this.houseList =this.houseList.concat( data.body.list.map(item=>{
            return{
                ...item,
                houseImg:"http://47.102.145.189:8009"+item.houseImg
            }
        }))
        //this.finished = true;
        this.loading = false;
      }
      
      
    },
    addTagsActive(arr) {
      return arr.map((item) => {
        return {
          ...item,
          active: false,
        };
      });
    },
    areaFilter(arr) {
      let city_list = {};
      let county_list = {};
      for (const _item of arr) {
        _item.children.forEach((item, ind) => {
          _item.label == "区域"
            ? (city_list[100000 + (ind + 1) * 100] = item.label)
            : (city_list[110000 + (ind + 1) * 100] = item.label);
          item.children &&
            item.children.forEach((v, i) => {
              _item.label == "区域"
                ? (county_list[100000 + (ind + 1) * 100 + i] = v.label)
                : (county_list[110000 + (ind + 1) * 100 + i] = v.label);
            });
        });
      }
      this.areaList.city_list = city_list;
      this.areaList.county_list = county_list;
    },
    priceOrRentFilter(arr) {
      let priceList = {};
      arr.forEach((item) => {
        priceList[item.value] = item.label;
      });
      return priceList;
    },
    onLoad() {
      if(this.houseList.length >= this.houseCount){
        return //Toast('没有更多数据了');
      } 
      this.gethouse();
    },
    onRefresh() {
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    goToDetail(id){
      this.$router.push('/detail/'+id)
    }
  },
};
</script>

<style lang="less">
.loading{
    position: fixed;
    background: #fff;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.popmain {
  flex: 1;
  overflow-y: auto;
  .right-pop-item {
    margin:0 15px;
    .pop-item-title {
      margin: 20px 0;
      font-size: 15px;
    }
    .pop-item-wrapper {
      border-bottom: 1px solid #e5e5e5;
      padding-bottom: 14px;
      .pop-item-tag {
        display: inline-block;
        height: 32px;
        width: 70px;
        margin: 0 18px 15px 0;
        border: 1px solid #ddd;
        border-radius: 3px;
        line-height: 32px;
        text-align: center;
        font-size: 12px;
        color: #888;
        &.active {
          border: 1px solid #21b97a;
          color: #21b97a;
          background-color: #defaef;
        }
      }
    }
  }
}
.van-picker__bottom {
  height: 50px;
  border-top: 1px solid #ccc;
  display: flex;
  .sm-btn {
    width: 125px;
    color: #21b97a;
    height: 100%;
    font-size: 18px;
  }
  .big-btn {
    flex: 1;
    height: 100%;
    font-size: 18px;
    background: #21b97a;
  }
}
.findHouse-wrapper {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  // 选择器  确认 取消 菜单
  .van-picker__toolbar {
    display: none !important;
  }

  .van-dropdown-menu__bar {
    height: 40px;
  }
  .van-pull-refresh{
    padding: 0 15px;
  }
}
.van-skeleton__content{
  margin: 5px 0px;
  .van-skeleton__title{
    height: 35px;
  }
  .van-skeleton__row{
    height: 25px;
  }
}

</style>